import random
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

path = Service('./chromedriver')
driver = webdriver.Chrome(service=path)
# 打开网易云音乐排行榜页面
driver.get('https://music.163.com/#/discover/toplist')
# 最大化窗口
driver.maximize_window()
time.sleep(2)
f = driver.find_element(By.ID, 'g_iframe')  # 定位内层框架
driver.switch_to.frame(f)  # 焦点切换到内层框架
# <span data-res-id="2654867325" data-res-type="18" data-res-action="play" class="ply ">&nbsp;</span>
# 定位所有的播放键
play = driver.find_elements(By.XPATH, '//*[@data-res-action="play"]')
# 点击任意Top3的歌曲「播放」按钮
random.choice(play[1:4]).click()
# 点击关闭登录弹窗
driver.find_element(By.CLASS_NAME, '_3ENM2xDN').click()
time.sleep(2)
# 将第80首歌的播放按钮置于页面顶部
driver.execute_script("arguments[0].scrollIntoView();", play[80])
time.sleep(2)
# 播放第80首歌
play[80].click()
# 点击关闭登录弹窗
driver.find_element(By.CLASS_NAME, '_3ENM2xDN').click()
time.sleep(2)
driver.quit()
